package com.qin.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qin.entity.User;
import com.qin.service.UserService;
import com.qin.service.impl.UserServiceImpl;

import cn.hutool.log.StaticLog;

/**
 * 用来处理用户注册
 */
@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserService userService = new UserServiceImpl();

	/**
	 * 去注册页
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StaticLog.debug("进入注册页");
		request.getRequestDispatcher("WEB-INF/register.jsp").forward(request, response);
	}

	/**
	 * 完成注册操作，重定向到首页
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 拿到用户名、密码、邮箱
		StaticLog.info("已经进入注册页post方法，开始完成注册操作");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");

		// 创建一个user类、并设置相关属性
		User user = new User();
		user.setName(username);
		user.setPassword(password);
		user.setEmail(email);

		// 往数据库中添加用户
		Long userKey = userService.insertUser(user);
		user.setId(userKey);
		StaticLog.debug("开始往数据库中添加用户:{}",user);
		
		// 把这个用户放在session中，重定向到首页
		HttpSession session = request.getSession();
		session.setAttribute("user", user);
		session.setAttribute("shoppingNum", 0);

		StaticLog.info("注册功能完成！！");
		
		// 重定向到首页，发index请求
		response.getWriter().print(true);
		response.getWriter().flush();
		response.getWriter().close();
	}

}
